﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kunlun.Models;
using System.Web;
using System.IO;
using KunLunDirModels.Model;
using KunLunDirModels;

namespace Kunlun.BusinessLogic
{
    public class FlexSave
    {
        KunLunEntities eintites = new KunLunEntities();
        public int SaveXml(string xml, string tempid, string userid, string img, string worksid, string pagecount,string worksname)
        {
            try
            {

				string userpath = GetWorkPath(Convert.ToInt32(userid));
                int rd = new Random().Next(9999);
                string filename = DateTime.Now.Day+DateTime.Now.Millisecond+rd.ToString();
                if (worksid == "0")
                {
                    Works works = new Works();                    
                    works.TempID = int.Parse(tempid);
                    Templete temp = eintites.Templete.FirstOrDefault(f => f.Tid == works.TempID);
                    works.ProductID = temp.ProductID;
                    works.Thumbnail = String.Format("{0}{1}.jpg", userpath, filename).Replace("\\","/");
                    works.UserID = int.Parse(userid);
                    works.WorksName = worksname;
                    works.PagesCount = int.Parse(pagecount);
                    works.CreateTime = DateTime.Now;
                    works.ModifyTime = DateTime.Now;
                    works.XMLPath = String.Format("{0}{1}.xml", userpath, filename).Replace("\\", "/");
                    works.IsMake = true;
                    eintites.Works.Add(works);
                    eintites.SaveChanges();
                    File.WriteAllText(String.Format("{0}{1}{2}.xml", WebLog.Works, userpath, filename), HttpUtility.UrlDecode(xml, Encoding.UTF8));

                    byte[] bty = Convert.FromBase64String(img);
                    System.IO.File.WriteAllBytes(String.Format("{0}{1}{2}.jpg", WebLog.Works, userpath, filename), bty);
                    return works.ID;
                }

                else
                {
                    int workid = int.Parse(worksid);
                    Works works = eintites.Works.Single(w => w.ID == workid);
                    works.TempID = int.Parse(tempid);
                  
                    works.UserID = int.Parse(userid);
                    works.WorksName = worksname;
                    works.PagesCount = int.Parse(pagecount);
                    works.ModifyTime = DateTime.Now;
                    works.IsMake = true;                
                    eintites.SaveChanges();
                    if (File.Exists(WebLog.Works + works.XMLPath))
                    {
                        File.Delete(WebLog.Works + works.XMLPath);
                    }
                    if (File.Exists(WebLog.Works + works.Thumbnail))
                    {
                        File.Delete(WebLog.Works + works.Thumbnail);
                    }
                    File.WriteAllText(String.Format("{0}{1}", WebLog.Works, works.XMLPath), HttpUtility.UrlDecode(xml, Encoding.UTF8));
                    byte[] bty = Convert.FromBase64String(img);
                    System.IO.File.WriteAllBytes(String.Format("{0}{1}", WebLog.Works, works.Thumbnail), bty);
                    return workid;
                }
               
                
            }
            catch (Exception ex)
            {
                WebLog.ErrorLog(ex);
                return 0;
            }
        }


		public int SaveFrameWork(int userID, int photoID, int width, int height,DivFrame frame) {
			KunLunEntities enitites = new KunLunEntities();
			string userpath = GetWorkPath(userID);
			int rd = new Random().Next(9999);
			string filename = DateTime.Now.Day + DateTime.Now.Millisecond + rd.ToString();
			Works w = new Works();
			w.IsMake = true;
			w.CreateTime = DateTime.Now;
			w.ModifyTime = DateTime.Now;
			w.Width = width;
			w.Height = height;
			w.WorkType = (int)WorkTypeEnum.框画;
			w.ProductID = WebLog.DivFrameID;
			w.TempID = enitites.Templete.FirstOrDefault().Tid;
			w.WorksName = "自定义" + width + "x" + height + "框画";
			w.UserID = userID;
			w.IsEdit = true;
			w.Price = GetFrameDivMoney(frame);
			w.Thumbnail = enitites.Consumer_pic.FirstOrDefault(o => o.ID == photoID).ThumUrl;
			string xml = SerializerBuilder.SerilizeAnXml(frame);
			File.WriteAllText(String.Format("{0}{1}{2}.xml", WebLog.Works, userpath, filename), HttpUtility.UrlDecode(xml.Trim(), Encoding.UTF8));
			w.XMLPath = String.Format("{0}{1}.xml", userpath, filename).Replace("\\", "/");
			enitites.Works.Add(w);
			enitites.SaveChanges();
			return w.ID;
		}

		public void UpdateFrameWork(int workID, int photoID, int width, int height,DivFrame frame){
			KunLunEntities enitites = new KunLunEntities();
			Works w = enitites.Works.FirstOrDefault(o => o.ID == workID);
			w.IsMake = true;
			w.ModifyTime = DateTime.Now;
			w.PagesCount = width * height;
			w.WorkType = (int)WorkTypeEnum.框画;
			w.WorksName = "自定义" + width + "x" + height + "框画";
			w.IsEdit = true;
			w.Price = GetFrameDivMoney(frame);
			w.Thumbnail = enitites.Consumer_pic.FirstOrDefault(o => o.ID == photoID).ThumUrl;
			string xml = SerializerBuilder.SerilizeAnXml(frame);
			File.WriteAllText(String.Format("{0}{1}", WebLog.Works, w.XMLPath), HttpUtility.UrlDecode(xml.Trim(), Encoding.UTF8));
			enitites.SaveChanges();
		}

		public List<Works> GetUserWorks(int index, int size, WorkTypeEnum t, Dictionary<string, string> where) {
			KunLunEntities enitites = new KunLunEntities();
			int ti = (int)t;
			IQueryable<Works> query = enitites.Works.Where(o=>o.WorkType == ti);
			if (where != null) {
				if (where.ContainsKey("UserID")) {
					int uid = Convert.ToInt32(where["UserID"]);
					query = query.Where(o => o.UserID == uid);
				}
			}
			query = query.OrderBy(o => o.CreateTime);
			if (index != 0) {
				query = query.Skip(index * size);
			}
			if (size != 0) {
				query = query.Take(size);
			}

			return query.ToList();
		}

		public Works GetWork(int wid) {
			KunLunEntities enitites = new KunLunEntities();
			Works w = enitites.Works.FirstOrDefault(o => o.ID == wid);
			return w;
		}

		public Works DeleteWork(int wid, int uid) {
			KunLunEntities enitites = new KunLunEntities();
			Works w = enitites.Works.FirstOrDefault(o => o.ID == wid && o.UserID == uid && o.IsEdit);
			if (w != null) {
				File.Delete(String.Format("{0}{1}", WebLog.Works, w.XMLPath));
				enitites.Works.Remove(w);
				enitites.SaveChanges();
			}
			return w;
		}

		private string GetWorkPath(int userid) {
			string monthpath = String.Format("{0}-{1}\\", DateTime.Now.Year, DateTime.Now.Month);
			string userpath = String.Format("{0}-{1}\\{2}\\", DateTime.Now.Year, DateTime.Now.Month, userid);
			if (!Directory.Exists(WebLog.Works + monthpath)) {

				Directory.CreateDirectory(WebLog.Works + monthpath);
			}
			if (!Directory.Exists(WebLog.Works + userpath)) {

				Directory.CreateDirectory(WebLog.Works + userpath);
			}
			return userpath;
		}

		public decimal GetFrameDivMoney(DivFrame frame) {
			KunLunEntities enitites = new KunLunEntities();
			string fid = WebLog.DivFrameID;
			Product p = enitites.Product.FirstOrDefault(o => o.pid == fid);
			decimal money = 0;
			money += p.Kacaprice * frame.FrameH * frame.FrameW / 10000;
			foreach (DivFrameItem item in frame.FrameItems) {
				Product pc = eintites.Product.FirstOrDefault(o => o.pid == item.PID);
				item.Product = pc.Name;
				switch (item.Level) {
					case 0:
						money = frame.FrameW * frame.FrameH * p.Kacaprice / 10000;
						break;
					case 4:
						money = (frame.FrameW + frame.FrameH) * p.Kacaprice / 50;
						break;
					default:
						money = frame.FrameW * frame.FrameH * p.Kacaprice / 10000;
						break;
				}
			}
			return money;
		}
    }
}
